<template>
  <avue-crud :class="{noMenuHtml: noMenuHtml}" ref="bomCrud" :option="BOMoption" :data="BOMdata" :permission="bomPermissionList" v-model="bomForm" @row-save="scopeRowSave" @row-update="scopeRowUpdate" :before-open="beforeScopeOpen" @refresh-change="refreshBOMChange">
    <template slot-scope="{row}" slot="lossRate">
      {{row.lossRate==-1?'':row.lossRate+"%"}}
    </template>
    <template slot-scope="scope" slot="lossRateForm">
      <span style="padding:0 15px;font-size:12px">{{bomForm.lossRate==-1?'':bomForm.lossRate+"%"}}</span>
    </template>
    <template slot-scope="scope" slot="addScopeForm">
      <el-button type="primary" icon="el-icon-plus" @click="addScopeMaterial"></el-button>
    </template>
    <template slot="infoScopeForm" slot-scope="scope">
      <avue-crud class="noMenuHtml" :option="infoScopeOption" :data="childScopePrdBomList" @row-update="addScopeUpdate" @row-del="infoScopeRowDel">
        <template slot="menu" slot-scope="{row}">
          <el-tooltip v-if="clearSaveCancelEditBtn" class="item" effect="dark" content="删除" placement="bottom">
            <el-button icon="el-icon-delete" size="small" type="text" @click.stop="infoScopeRowDel(row.$index)"></el-button>
          </el-tooltip>
        </template>
      </avue-crud>
    </template>
    <template slot-scope="{row}" slot="menu">
      <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
        <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.bomCrud.rowView(row,row.$index)" v-if="viewBtn"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="$refs.bomCrud.rowEdit(row,row.$index)" v-if="editBtn"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
        <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowScopeDel(row)" v-if="delBtn&&row.directLeaderNo"></el-button>
      </el-tooltip>
    </template>
  </avue-crud>
</template>
<script>
import * as product from '@/views/publicbom/bom/ajax.js';
import { getMaterialgroupList } from '@/api/project/productData/baseData';
import { mapGetters, mapState } from 'vuex';
import { infoOption, BOMoption } from '@/const/project/bom';
import { getUnitList } from '@/api/basic/unit';

export default {
  props: {
    BOMdata: {
      type: Array,
    },
    addBtn: {
      type: Boolean,
    },
    viewBtn: {
      type: Boolean,
    },
    editBtn: {
      type: Boolean,
    },
    delBtn: {
      type: Boolean,
    },
    productNo: {
      type: String,
    },
    productName: {
      type: String,
    },
    productFlag: {
      type: String,
    },
    type: {
      type: String,
    },
    bomType: {
      type: String,
    },
    clearSaveCancelEditBtn: {
      type: Boolean,
    },
    noMenuHtml: {
      type: Boolean
    }
  },
  name: 'bom',
  data() {
    return {
      infoScopeOption: infoOption,
      BOMoption: BOMoption,
      bomForm: { topProductNo: '', directLeaderNo: '' },
      bommaterialList: [],
      childScopePrdBomList: [],
    };
  },
  created() {
    if (this.addBtn) {
      this.BOMoption.header = true;
      this.BOMoption.addBtn = true;
    } else {
      this.BOMoption.header = false;
      this.BOMoption.addBtn = false;
    }
    if (this.type == 'edit') {
      this.BOMoption.header = true;
      this.BOMoption.menu = true;
    } else {
      this.BOMoption.header = false;
      this.BOMoption.menu = false;
    }
    if (this.clearSaveCancelEditBtn) {
      this.infoScopeOption.cellBtn = false
      this.$set(this.infoScopeOption, 'cancelBtn', false)
      this.$set(this.infoScopeOption, 'delBtn', false)
    }
    getUnitList().then((res) => {
      let data = res.data.data;
      const column = this.findObject(this.infoScopeOption.column, 'unit');
      const column1 = this.findObject(this.BOMoption.column, 'unit');
      column.dicData = data.map((item) => {
        return {
          label: item.name + '(' + item.code + ')',
          value: item.code,
        };
      });
      column1.dicData = data.map((item) => {
        return {
          label: item.name + '(' + item.code + ')',
          value: item.code,
        };
      });
    });
    product.getMaterialTypeTree({ code: 'materials', dictKey: 'P,M,S' }).then((res) => {
      let data = res.data.data;
      const column1 = this.findObject(this.BOMoption.column, 'materialTypes');
      column1.dicData = data;
    });
  },
  computed: {
    ...mapGetters(['permission']), //权限映射
    ...mapState({
      headers: (state) => ({ 'Blade-Auth': `bearer ${state.user.token}` }),
    }),
    bomPermissionList() {
      //按钮权限设置
      return {
        addBtn: this.addBtn,
        viewBtn: this.viewBtn,
        delBtn: this.delBtn,
        editBtn: this.editBtn,
      };
    },
  },
  watch: {
    'bomForm.materialType'(newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        getMaterialgroupList({ materialType: newVal.join(',') }).then((res) => {
          let data = res.data.data;
          const column = this.findObject(this.BOMoption.group, 'materialGroupNo');
          if (res.data.data.length == 0) {
            column.dicData.length = 0;
            column.dicData = [];
          } else {
            column.dicData = data;
          }
        });
        product.materialList({ materialType: newVal[1] }).then((res) => {
          const column = this.findObject(this.BOMoption.group[0].column, 'bomNo');
          if (res.data.data.length == 0) {
            column.dicData = [{ label: '无数据', value: '', disabled: true }];
            this.bommaterialList.length = 0;
          } else {
            this.bommaterialList = res.data.data;
            column.dicData = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (newVal && newVal.length == 0) {
        this.findObject(this.BOMoption.group, 'materialGroupNo').dicData.length = 0;
        this.findObject(this.BOMoption.group, 'materialGroupNo').dicData = [];
        this.findObject(this.BOMoption.group, 'bomNo').dicData.length = 0;
        this.findObject(this.BOMoption.group, 'bomNo').dicData = [];
        this.$set(this.bomForm, 'materialGroupNo', null);
        this.$set(this.bomForm, 'bomNo', null);
      }
      if (oldVal && oldVal.length > 0 && newVal && newVal.length > 0 && newVal.join(',') !== oldVal.join(',')) {
        this.findObject(this.BOMoption.group, 'materialGroupNo').dicData.length = 0;
        this.findObject(this.BOMoption.group, 'materialGroupNo').dicData = [];
        this.findObject(this.BOMoption.group, 'bomNo').dicData.length = 0;
        this.findObject(this.BOMoption.group, 'bomNo').dicData = [];
        this.$set(this.bomForm, 'materialGroupNo', null);
        this.$set(this.bomForm, 'bomNo', null);
      }
    },
    'bomForm.materialGroupNo'(newVal, oldVal) {
      if (newVal && this.bomForm.materialType.length > 0) {
        this.$set(this.bomForm, 'bomNo', null);
        product.materialList({ materialType: this.bomForm.materialType[1], materialGroupNo: newVal }).then((res) => {
          const column = this.findObject(this.BOMoption.group[0].column, 'bomNo');
          if (res.data.data.length == 0) {
            column.dicData = [{ label: '无数据', value: '', disabled: true }];
            this.bommaterialList.length = 0;
          } else {
            this.bommaterialList = res.data.data;
            column.dicData = res.data.data.map((item) => {
              return {
                label: item.materialName + '(' + item.materialNo + ')',
                value: item.materialNo,
              };
            });
          }
        });
      }
      if (!newVal || (newVal && this.bomForm.materialType.length == 0)) {
        this.$set(this.bomForm, 'bomNo', null);
        this.$forceUpdate();
      }
      if (oldVal) {
        this.$set(this.bomForm, 'bomNo', null);
      }
    },
  },
  methods: {
    refreshBOMChange() {
      this.$emit('getBom');
    },
    addScopeMaterial() {
      if (!this.bomForm.bomNo) {
        this.$message.error('请选择要添加的物料');
        return;
      }
      if (this.bomForm.bomNo) {
        if (this.childScopePrdBomList.length > 0) {
          let isHave = false;
          isHave = this.childScopePrdBomList.some((item) => item.materialNo == this.bomForm.bomNo);
          if (isHave) {
            this.$message.error('物料已添加，不可重复添加');
            return;
          }
        }
        this.bommaterialList.every((item) => {
          if (this.bomForm.bomNo == item.materialNo) {
            if (this.bomForm.materialNo && this.bomForm.materialNo == this.bomForm.bomNo) {
              this.$message.error('添加的物料不可以与上级物料相同');
            } else {
              item.$cellEdit = true;
              item.id = null
              this.childScopePrdBomList.push(item);
            }
            return false;
          } else {
            return true;
          }
        });
      }
    },
    addScopeUpdate(form, index, done, loading) {
      done();
    },
    infoScopeRowDel(row, index) {
      this.childScopePrdBomList.splice(index, 1);
    },
    validScopeFunction(data) {
      let equipMsg = '';
      if (data.length > 0) {
        data.every((item, index) => {
          if (!item.quota) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入定额`;
            this.$message.error(equipMsg);
            return false;
          } else if (item.quota) {
            let reg = /^[0-9]*\/+[1-9][0-9]*$/; //分数验证
            let reg1 = /^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/ // 请输入100以内的正整数或最多两位小数
            if (item.quota == '0') {
              equipMsg = `【BOM组成】第${index + 1}行 定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)`;
              this.$message.error(equipMsg);
              return false;
            }
            if (reg.test(item.quota)) {
              let arr = item.quota.split('/');
              if (arr[0] == 0 || arr[1] == 0 || arr[0] >= arr[1]) {
                equipMsg = `【BOM组成】第${index + 1}行 定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)`;
                this.$message.error(equipMsg);
                return false;
              }
            }
            if (!reg.test(item.quota) && !reg1.test(item.quota)) {
              equipMsg = `【BOM组成】第${index + 1}行 定额请输入100以内的正整数或最多四位小数，或小于1的分数(如1/2700)`;
              this.$message.error(equipMsg);
              return false;
            }
          }
          let reg1 = /^(0|[1-9]{1}|[1-9]{1}[0-9]{1})((\.\d{1,2})?)$|100$|100.00$|100.0$/ // 请输入100以内的正整数或最多两位小数
          if (!item.lossRate) {
            equipMsg = `【BOM组成】第${index + 1}行 请输入损耗率`;
            this.$message.error(equipMsg);
            return false;
          } else if (!reg1.test(item.lossRate)) {
            equipMsg = `【BOM组成】第${index + 1}行 损耗率请输入10以内的数，且最多两位小数`;
            this.$message.error(equipMsg);
            return false;
          } else {
            return true;
          }
        });
      }
      if (equipMsg) {
        return false;
      } else {
        return true;
      }
    },
    scopeRowSave(row, done, loading) {
      let valid = this.validScopeFunction(this.childScopePrdBomList);
      if (!valid) {
        loading();
        return;
      }
      let children = this.childScopePrdBomList.map((item) => {
        if (item.id) {
          delete item.id;
        }
        return item;
      });
      if (this.bomType == 'product') {
        row.dataSource = '1';
      } else {
        row.dataSource = '2';
      }
      let content = { ...row, childPrdBomList: children };
      product.bomSave(content).then(
        () => {
          done();
          this.$emit('getBom');
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          loading();
          // console.log(error);
        }
      );
    },
    scopeRowUpdate(row, index, loading, done) {
      let valid = this.validScopeFunction(this.childScopePrdBomList);
      if (!valid) {
        done();
        return;
      }
      let content = { ...row, childPrdBomList: this.childScopePrdBomList };
      product.bomUpdate(content).then(
        () => {
          loading();
          this.$emit('getBom');
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          done();
        }
      );
    },
    rowScopeDel(row) {
      //行内的删除事件触发
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return product.bomRemove(row.id);
        })
        .then(() => {
          this.$emit('getBom');
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    getMaterialTypeList(dictKey) {
      product.getMaterialTypeTree({ code: 'materials', dictKey: dictKey }).then((res) => {
        let data = res.data.data;
        const column = this.findObject(this.BOMoption.group, 'materialType');
        column.dicData = data;
      });
    },
    beforeScopeOpen(done, type) {
      this.childScopePrdBomList.length = 0;
      this.childScopePrdBomList = [];
      this.$set(this.bomForm, 'materialType', null);
      this.$set(this.bomForm, 'materialGroupNo', null);
      this.$set(this.bomForm, 'bomNo', null);
      const column0 = this.findObject(this.BOMoption.group, 'materialGroupNo');
      column0.dicData.length = 0;
      column0.dicData = [];
      const column = this.findObject(this.BOMoption.group, 'bomNo');
      column.dicData.length = 0;
      column.dicData = [];
      const column1 = this.findObject(this.BOMoption.column, 'lossRate');
      let dictKey = '';
      if (type == 'add') {
        if (this.productFlag == 'P') {
          dictKey = 'P,M';
        } else {
          dictKey = 'M';
        }
        this.getMaterialTypeList(dictKey);
      } else if (type == 'edit') {
        if (this.bomForm.productFlag == 'P') {
          dictKey = 'P,M';
        } else {
          dictKey = 'M';
        }
        this.getMaterialTypeList(dictKey);
      }

      if (['edit', 'view'].includes(type)) {
        product.bomDetail(this.bomForm.id).then((res) => {
          this.bomForm = res.data.data;
          this.childScopePrdBomList = res.data.data.childPrdBomList;
          // this.childScopePrdBomList = res.data.data.children;
          if (!this.bomForm.directLeaderNo) {
            this.$set(this.bomForm, 'productName', this.productName);
            this.$set(this.bomForm, 'materialNo', this.productNo);
          }
        });
        if (type == 'view') {
          column1.formslot = true;
          this.infoScopeOption.menu = false;
        } else {
          column1.formslot = false;
          this.infoScopeOption.menu = true;
        }
      } else {
        this.$set(this.bomForm, 'productName', this.productName);
        this.$set(this.bomForm, 'materialNo', this.productNo);
      }
      if (!this.bomForm.directLeaderNo) {
        this.BOMoption.column[2].editDisplay = true
        this.BOMoption.column[3].editDisplay = false
        this.BOMoption.column[6].editDisplay = false
        this.BOMoption.column[7].editDisplay = false
        this.BOMoption.column[8].editDisplay = false
        this.BOMoption.column[9].editDisplay = false
        this.BOMoption.column[10].editDisplay = false
        this.BOMoption.column[11].editDisplay = false
        this.BOMoption.column[12].editDisplay = false
      } else {
        this.BOMoption.column[2].editDisplay = false
        this.BOMoption.column[3].editDisplay = true
        this.BOMoption.column[6].editDisplay = true
        this.BOMoption.column[7].editDisplay = true
        this.BOMoption.column[8].editDisplay = true
        this.BOMoption.column[9].editDisplay = true
        this.BOMoption.column[10].editDisplay = true
        this.BOMoption.column[11].editDisplay = true
        this.BOMoption.column[12].editDisplay = true
      }
      done();
    },
  },
};
</script>
<style lang="scss" scoped>
</style>